package org.kl.bf.web.basic;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.kl.bf.entity.basic.CodeValues;
import org.kl.bf.entity.easyui.EasyuiTreeNode;
import org.kl.bf.entity.easyui.EasyuiUtils;
import org.kl.bf.entity.easyui.Json;
import org.kl.bf.service.basic.CodeValuesService;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

/**
 * 系统配置
 * 
 * @Author hqm
 * @CreateTime 2014-3-13 下午9:34:36
 */
@Controller
@RequestMapping(value = "/basic/codeValues")
public class CodeValuesController extends BasicController {
	@Autowired
	private CodeValuesService codeValuesService;

	@RequiresPermissions("codeTable:list")
	@RequestMapping(value = "layoutTest", method = RequestMethod.GET)
	public String layoutTest() {
		return "basic/layoutTest";
	}

	@RequiresPermissions("codeTable:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/codeValuesList";
	}

	@RequiresPermissions("codeTable:list")
	@RequestMapping(value = "dataGrid", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "sort", defaultValue = "createTime") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		List<CodeValues> codeValues;
		/*if (StringUtils.isBlank(request.getParameter("search_EQ_codeTable.id"))) {
			codeValues = codeValuesService.getCodeValues();
			// codeValues = new ArrayList<CodeValues>();
		} else {*/
			Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
			codeValues = codeValuesService.getAllCodeValues(searchParams, sortType, orderType);
		
		return EasyuiUtils.buildEasyuiGridJsonString(codeValues, codeValues.size());
	}

	/**
	 * 树形下拉框
	 * 
	 * @param sortType
	 * @param orderType
	 * @param model
	 * @param request
	 * @return
	 */
	@RequiresPermissions("codeTable:update")
	@RequestMapping(value = "comboTree", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String comboTree(Model model, ServletRequest request) {
		List<CodeValues> codeValues;
		if (StringUtils.isBlank(request.getParameter("search_EQ_codeTable.id"))) {
			codeValues = new ArrayList<CodeValues>();
		} else {
			Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
			codeValues = codeValuesService.getAllCodeValues(searchParams, null, null);
		}
		List<EasyuiTreeNode> plainTree = new ArrayList<EasyuiTreeNode>();
		for (CodeValues cv : codeValues) {
			EasyuiTreeNode one = new EasyuiTreeNode();
			one.setId(cv.getId());
			one.setText(cv.getCodeName());
			one.setPid(cv.getPid());
			one.setIconCls(cv.getIconCls());
			plainTree.add(one);
		}
		String result = jsonMapper.toJson(plainTree);
		return result;
	}

	@RequiresPermissions("codeTable:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("codeValues") CodeValues codeValues, RedirectAttributes redirectAttributes) {
		try {
			codeValuesService.saveCodeValues(codeValues);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("编辑失败[" + e.getMessage() + "]", false, null);
		}
		return ajaxMsg("编辑成功", true, null);
	}

	@RequiresPermissions("codeTable:delete")
	@RequestMapping(value = "delete", produces = MediaTypes.JAVASCRIPT_UTF_8, method = RequestMethod.POST)
	@ResponseBody
	public String delete(@RequestParam(value = "ids", defaultValue = "") String ids, RedirectAttributes redirectAttributes) {
		if (StringUtils.isBlank(ids)) {
			return ajaxMsg("传入参数为空，无法执行删除操作", false, null);
		}
		Json json = new Json();
		try {
			int count = codeValuesService.deleteCodeValues(ids);
			json.setMsg("成功删除" + count + "条");
			json.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			json.setMsg("删除失败[" + e.getMessage() + "]");
			json.setSuccess(false);
		}
		return jsonMapper.toJson(json);
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getCodeValues(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("codeValues", codeValuesService.getCodeValues(id));
		}
	}
}
